package com.shbaiche.bifenba.ui.home;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.adapter.home.HomeInfoAdapter;
import com.shbaiche.bifenba.adapter.home.SearchHistoryAdapter;
import com.shbaiche.bifenba.adapter.home.SearchHotMatchAdapter;
import com.shbaiche.bifenba.adapter.home.SearchQuiteAdapter;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.video.ArticleListMessage;
import com.shbaiche.bifenba.model.video.ArticleVo;
import com.shbaiche.bifenba.model.video.HotMatchesMessage;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;


public class SearchActivity extends Activity {
    public static final String EXTRA_KEY_TYPE = "extra_key_type";
    public static final String EXTRA_KEY_KEYWORD = "extra_key_keyword";
    public static final String KEY_SEARCH_HISTORY_KEYWORD = "key_search_history_keyword";
    private EditText mKeywordEt;
    private TextView mOperationTv;
    private String mType;


    private SearchHistoryAdapter mArrAdapter;
    private SearchHotMatchAdapter mHotMatchAdapter;
    private SearchQuiteAdapter mQuiteAdapter;
    private SharedPreferences mPref;

    private ListView hisLv, hotMatchLv;

    List<com.shbaiche.bifenba.model.match.MatchesVo> matchesVosList;

    private RecyclerView dataLv;

    private GridView quiteGv;

    private Dialog dg;

    private TextView hotTv;

    private LinearLayout mSearchHistoryLl, mSearchHotLl, mSearchQuite, mDataLayout;
    private List<String> mHistoryKeywords, mQuiteList;
    HomeInfoAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPref = getSharedPreferences("search",
                Activity.MODE_PRIVATE);

        mType = getIntent().getStringExtra(EXTRA_KEY_TYPE);
        String keyword = getIntent().getStringExtra(EXTRA_KEY_KEYWORD);
        if (!TextUtils.isEmpty(keyword)) {
            mKeywordEt.setText(keyword);
        }
        mHistoryKeywords = new ArrayList<String>();

        mQuiteList = new ArrayList<>();
        mQuiteList.add("英超");
        mQuiteList.add("意甲");
        mQuiteList.add("德甲");
        mQuiteList.add("西甲");
        mQuiteList.add("法甲");

        setContentView(R.layout.activity_search);

        final ImageView clearKeywordIv = (ImageView) findViewById(R.id.clear_keyword_iv);
        hotTv = (TextView) findViewById(R.id.hot_tv);
        clearKeywordIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mKeywordEt.setText("");
                v.setVisibility(View.GONE);
            }
        });
        mKeywordEt = (EditText) findViewById(R.id.tab_bar_keyword_et);

        mKeywordEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    return true;
                }
                return false;
            }
        });
        mKeywordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    mOperationTv.setText("搜索");
                    clearKeywordIv.setVisibility(View.GONE);
                    if (mHistoryKeywords.size() > 0) {
                        mSearchHistoryLl.setVisibility(View.VISIBLE);
                        mSearchHotLl.setVisibility(View.VISIBLE);
                        mSearchQuite.setVisibility(View.VISIBLE);
                        mDataLayout.setVisibility(View.GONE);
                    } else {
                        mSearchHistoryLl.setVisibility(View.GONE);
                        mSearchHotLl.setVisibility(View.GONE);
                        mSearchQuite.setVisibility(View.GONE);
                    }
                } else {
                    mSearchHistoryLl.setVisibility(View.GONE);
                    mSearchHotLl.setVisibility(View.GONE);
                    mSearchQuite.setVisibility(View.GONE);
                    mOperationTv.setText("搜索");
                    clearKeywordIv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mOperationTv = (TextView) findViewById(R.id.tab_bar_cancel_tv);
        mOperationTv.setText("搜索");
        mOperationTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mKeywordEt.getText().length() > 0) {
                    Toast.makeText(getApplicationContext(), "搜索中...", Toast.LENGTH_SHORT).show();
                    try {
                        save();
                        load(mKeywordEt.getText().toString());
                    } catch (Exception e) {

                    }
                } else {
                    //finish();
                }
            }
        });
        initSearchHistory();

        dg = new Dialog(this);
        dg.setContentView(R.layout.view_loading);


        HotMatchesMessage msg = new HotMatchesMessage();

        NetApi.HotMatches(msg, new JsonCallback<TransMessage>() {

            @Override
            public void onFail(Call call, Exception e, int id) {
                dg.hide();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onResponse(TransMessage response, int id) {
                Gson gson = new Gson();
                HotMatchesMessage msg = gson.fromJson(response.getMessage(), HotMatchesMessage.class);
                if (msg != null && msg.getVoList() != null) {
                    matchesVosList = msg.getVoList();
                    if (matchesVosList == null || matchesVosList.size() == 0) {
                        hotTv.setVisibility(View.GONE);
                    }
                    if (mHotMatchAdapter == null) {
                        mHotMatchAdapter = new SearchHotMatchAdapter(SearchActivity.this, matchesVosList);
                        hotMatchLv.setAdapter(mHotMatchAdapter);
                        hotMatchLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                if (matchesVosList.get(i) != null)
                                    mKeywordEt.setText(matchesVosList.get(i).getCompeteName() + "");
                                mSearchHistoryLl.setVisibility(View.GONE);
                                mSearchHotLl.setVisibility(View.GONE);
                                mSearchQuite.setVisibility(View.GONE);
                            }
                        });
                    }
                } else {


                }

            }
        });
    }

    public void initSearchHistory() {
        mSearchHistoryLl = (LinearLayout) findViewById(R.id.search_history_ll);
        hisLv = (ListView) findViewById(R.id.search_history_lv);
        mSearchHotLl = (LinearLayout) findViewById(R.id.search_history_hot_match_ll);
        hotMatchLv = (ListView) findViewById(R.id.search_history_hot_match);

        mDataLayout = (LinearLayout) findViewById(R.id.search_history_data_ll);
        dataLv = (RecyclerView) findViewById(R.id.search_history_data_lv);
//创建LinearLayoutManager 对象
        LinearLayoutManager layoutmanager = new LinearLayoutManager(this);
        layoutmanager.setOrientation(LinearLayoutManager.VERTICAL);
        dataLv.setLayoutManager(layoutmanager);

        mSearchQuite = (LinearLayout) findViewById(R.id.search_history_quite_ll);
        quiteGv = (GridView) findViewById(R.id.search_history_quite_gridview);
        String history = mPref.getString(KEY_SEARCH_HISTORY_KEYWORD, "");
        if (!TextUtils.isEmpty(history)) {
            List<String> list = new ArrayList<String>();
            for (Object o : history.split(",")) {
                list.add((String) o);
            }
            mHistoryKeywords = list;
        }
        if (mHistoryKeywords.size() > 0) {
            mSearchHistoryLl.setVisibility(View.VISIBLE);
            mSearchHotLl.setVisibility(View.VISIBLE);
            mSearchQuite.setVisibility(View.VISIBLE);
        } else {
            mSearchHistoryLl.setVisibility(View.GONE);
            mSearchHotLl.setVisibility(View.GONE);
            mSearchQuite.setVisibility(View.GONE);
        }
        mArrAdapter = new SearchHistoryAdapter(this, mHistoryKeywords);
        hisLv.setAdapter(mArrAdapter);
        hisLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mKeywordEt.setText(mHistoryKeywords.get(i));
                mSearchHistoryLl.setVisibility(View.GONE);
                mSearchHotLl.setVisibility(View.GONE);
                mSearchQuite.setVisibility(View.GONE);
                load(mHistoryKeywords.get(i));
            }
        });
        mArrAdapter.notifyDataSetChanged();

        mQuiteAdapter = new SearchQuiteAdapter(this, mQuiteList);
        quiteGv.setAdapter(mQuiteAdapter);
        quiteGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mKeywordEt.setText(mQuiteList.get(i));
                mSearchHistoryLl.setVisibility(View.GONE);
                mSearchHotLl.setVisibility(View.GONE);
                mSearchQuite.setVisibility(View.GONE);
            }
        });
    }

    public void save() {
        String text = mKeywordEt.getText().toString();
        String oldText = mPref.getString(KEY_SEARCH_HISTORY_KEYWORD, "");
        if (!TextUtils.isEmpty(text) && !(oldText.contains(text))) {
            if (mHistoryKeywords.size() > 2) {
//                Toast.makeText(this,"最多保存5条历史",Toast.LENGTH_SHORT).show();
                mHistoryKeywords.remove(mHistoryKeywords.size() - 1);
            }

            mHistoryKeywords.add(0, text);

            String textStr = "";
            for (int i = 0; i < mHistoryKeywords.size(); i++) {
                if (i != 0 && !"".equals(mHistoryKeywords.get(i))) {
                    if (!TextUtils.isEmpty(textStr)) {
                        textStr = textStr + "," + mHistoryKeywords.get(i);
                    } else {
                        textStr = mHistoryKeywords.get(i);
                    }
                } else if (i == 0 && !"".equals(mHistoryKeywords.get(i))) {
                    textStr = mHistoryKeywords.get(i);
                }
            }
            SharedPreferences.Editor editor = mPref.edit();
            editor.putString(KEY_SEARCH_HISTORY_KEYWORD, textStr);
            editor.commit();
        }
        mArrAdapter.setData(mHistoryKeywords);
    }

    private void load(String search) {
        if (TextUtils.isEmpty(search)) {
            ToastUtil.show("搜索内容不能为空！");
            return;
        }
        if (adapter != null)
            adapter.clear();
        adapter = null;
        dg.show();
        mDataLayout.setVisibility(View.VISIBLE);
        mSearchHistoryLl.setVisibility(View.GONE);
        mSearchHotLl.setVisibility(View.GONE);
        mSearchQuite.setVisibility(View.GONE);
        ArticleListMessage msg = new ArticleListMessage();
//        msg.setType(ArticleGroupVo.Type.VIDEO);
        msg.setSearch(search);

        NetApi.videoList(msg, new JsonCallback<TransMessage>() {

            @Override
            public void onFail(Call call, Exception e, int id) {
                dg.hide();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
                dg.hide();
            }

            @Override
            public void onResponse(TransMessage response, int id) {
                dg.hide();
                Gson gson = new Gson();
                ArticleListMessage msg = gson.fromJson(response.getMessage(), ArticleListMessage.class);

                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {


                    List<ArticleVo> listData = msg.getList();
                    if (adapter == null) {
                        adapter = new HomeInfoAdapter(SearchActivity.this, listData);
                        dataLv.setAdapter(adapter);
                    }
                } else {


                }

            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        String type = intent.getStringExtra(EXTRA_KEY_TYPE);
        String keyword = intent.getStringExtra(EXTRA_KEY_KEYWORD);

        if (!TextUtils.isEmpty(keyword)) {
            mKeywordEt.setText(keyword);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDestroy() {
        if (dg != null) {
            dg.dismiss();
            dg = null;
        }
        super.onDestroy();
    }
}
